//
//  GetDeviceViewController.m
//  Rail
//
//  Created by hychen on 2018/7/22.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "GetDeviceViewController.h"
#import "WarnDetailTableViewCell.h"
#import "ButtonTableViewCell.h"
#import "DeviceListTableViewCell.h"

#import "ScanViewController.h"
#import "SelectGetDeviceListViewController.h"
#import "SelectUserViewController.h"
#import "WriteCustomerViewController.h"
#import "DeviceSelectUserViewController.h"

@interface GetDeviceViewController ()
@property (nonatomic, strong) NSArray *deviceArray;
@property (nonatomic, strong) NSArray *userArray;

@property (nonatomic, strong) DeviceInfoModel *selectDeviceModel;
@property (nonatomic, strong) DeviceUserInfoModel *userModel;

@property (nonatomic, copy) NSString *deviceNo;
@property (nonatomic, copy) NSString *deviceName;
@property (nonatomic, copy) NSString *areaName;

@property (nonatomic, copy) NSString *userName;
@property (nonatomic, copy) NSString *mobile;

@property (nonatomic, copy) NSString *userType;
@end

@implementation GetDeviceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem addSimpleTitleView:@"领用设备"];
    self.tableView.mj_header = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *array = [self.dataArray objectAtIndex:section];
    return array.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = Color_Background;
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10.f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dict = [[self.dataArray objectAtIndexSafe:indexPath.section] objectAtIndexSafe:indexPath.row];
    if (![dict isKindOfClass:[NSDictionary class]]) {
        return [UITableViewCell new];
    }
    BMWeakSelf
    if ([[dict objectForKeySafe:@"type"] isEqualToString:@"desc"]) {
        WarnDetailTableViewCell *cell = [WarnDetailTableViewCell cellWithTableView:tableView class:[WarnDetailTableViewCell class]];
        cell.contentLabel.textAlignment = NSTextAlignmentLeft;
        cell.titleLabel.text = [dict objectForKeySafe:@"title"];
        cell.contentLabel.text = [dict objectForKeySafe:@"content"];
        cell.showLine = YES;
        cell.rightConstraints.constant = 5;
        return cell;
    }
    else if ([[dict objectForKeySafe:@"type"] isEqualToString:@"list"]) {
        DeviceListTableViewCell *cell = [DeviceListTableViewCell cellWithInitStyleTableView:tableView class:[DeviceListTableViewCell class]];
        cell.array = [dict objectForKeySafe:@"data"];
        [cell setBlockClickButton:^(NSString *sign) {
            [weakSelf goToVcWithSign:sign];
        }];
        return cell;
    }
    else if ([[dict objectForKeySafe:@"type"] isEqualToString:@"button"]) {
        ButtonTableViewCell *cell = [ButtonTableViewCell cellWithTableView:tableView class:[ButtonTableViewCell class]];
        cell.buttonTitle = [dict objectForKeySafe:@"title"];
        [cell setBlockClickEventButton:^{
            [weakSelf requestData];
        }];
        return cell;
    }
    else {
        return [UITableViewCell new];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dict = [[self.dataArray objectAtIndexSafe:indexPath.section] objectAtIndexSafe:indexPath.row];
    if (![dict isKindOfClass:[NSDictionary class]]) {
        return 0;
    }
    if ([[dict objectForKeySafe:@"type"] isEqualToString:@"desc"]) {
        return 45;
    }
    else if ([[dict objectForKeySafe:@"type"] isEqualToString:@"list"]) {
        return 100;
    }
    else if ([[dict objectForKeySafe:@"type"] isEqualToString:@"button"]) {
        return 100;
    }
    else {
        return 0;
    }
}

#pragma mark - 网络请求
- (void)requestData {
    if (![self.deviceNo objectIsNotEmpty] || ![self.deviceName objectIsNotEmpty]) {
        Show_Msg_Error(@"请选择设备")
        return;
    }
    if (![self.userName objectIsNotEmpty] || ![self.mobile objectIsNotEmpty]) {
        Show_Msg_Error(@"请选择用户")
        return;
    }
    
    if ([self.selectDeviceModel.typecode isEqualToString:@"VOIP-A"]) {
        [self requestTbkDevice];
    }
    else if ([self.selectDeviceModel.typecode isEqualToString:@"GPS"]){
        [self requestLocateDevice];
    }
    else {
        Show_Msg_Error(@"类型出错")
    }
}

- (void)requestTbkDevice {
    Show_SV_NoMsg
    NSString *account = @"";
    NSString *mobile = @"";
    NSString *username = @"";
    NSString *company = @"";
    if ([self.userType isEqualToString:@"0"]) {
        account = self.userModel.account?:[GlobalManage sharedManage].userInfoModel.account;
        mobile = self.userModel.mobile?:[GlobalManage sharedManage].userInfoModel.mobile;
        username = self.userModel.username?:[GlobalManage sharedManage].userInfoModel.username;
        company = self.userModel.company?:[GlobalManage sharedManage].userInfoModel.username;
    }
    else if ([self.userType isEqualToString:@"1"]) {
        account = self.userModel.account;
        mobile = self.userModel.mobile;
        username = self.userModel.username;
        company = self.userModel.company;
    }
    BMWeakSelf
    [HttpRequest getTbkDeviceWithAccount:account userType:self.userType mobile:mobile userName:username company:company deviceId:self.selectDeviceModel.deviceid success:^(id object) {
        Show_Msg_Success(@"设备领用成功")
        if (weakSelf.BlockGetDeviceSuccess) {
            weakSelf.BlockGetDeviceSuccess(weakSelf.userName);
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
    } failure:^(NSString *code, NSString *msg) {
        Show_Msg_Error(msg?:@"设备领用失败")
    }];
}

- (void)requestLocateDevice {
    Show_SV_NoMsg
    NSString *account = @"";
    NSString *mobile = @"";
    NSString *username = @"";
    NSString *company = @"";
    if ([self.userType isEqualToString:@"0"]) {
        account = self.userModel.account?:[GlobalManage sharedManage].userInfoModel.account;
        mobile = self.userModel.mobile?:[GlobalManage sharedManage].userInfoModel.mobile;
        username = self.userModel.username?:[GlobalManage sharedManage].userInfoModel.username;
        company = self.userModel.company?:[GlobalManage sharedManage].userInfoModel.username;
    }
    else if ([self.userType isEqualToString:@"1"]) {
        mobile = self.userModel.mobile;
        username = self.userModel.username;
        company = self.userModel.company;
    }
    
    BMWeakSelf
    [HttpRequest getLocateDeviceWithDeviceId:self.selectDeviceModel.deviceid UserType:self.userType userAccount:account mobile:mobile username:username company:company success:^(id object) {
        Show_Msg_Success(@"设备领用成功")
        if (weakSelf.BlockGetDeviceSuccess) {
            weakSelf.BlockGetDeviceSuccess(weakSelf.userName);
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
    } failure:^(NSString *code, NSString *msg) {
        Show_Msg_Error(msg?:@"设备领用失败")
    }];
}

#pragma mark - 跳转
- (void)goToVcWithSign:(NSString *)sign {
    BMWeakSelf
    if ([sign isEqualToString:@"scandevice"]) {
        ScanViewController *vc = [[ScanViewController alloc] init];
        [vc setBlockSuccessPopBack:^(NSString *result) {
            //
#warning scan todo
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if ([sign isEqualToString:@"scanuser"]) {
        ScanViewController *vc = [[ScanViewController alloc] init];
        [vc setBlockSuccessPopBack:^(NSString *result) {
            //
#warning scan todo
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if ([sign isEqualToString:@"selectdevice"]) {
        SelectGetDeviceListViewController *vc = [SelectGetDeviceListViewController new];
        [vc setBlockSelectDevice:^(DeviceInfoModel *model) {
            weakSelf.selectDeviceModel = model;
            [weakSelf.tableView reloadData];
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if ([sign isEqualToString:@"selectuser"]) {
        DeviceSelectUserViewController *vc = [DeviceSelectUserViewController new];
        [vc setBlockSelectUser:^(DeviceUserInfoModel *model) {
            weakSelf.userType = @"0";
            weakSelf.userModel = model;
            weakSelf.userName = model.username;
            weakSelf.mobile = model.mobile;
            [weakSelf.tableView reloadData];
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if ([sign isEqualToString:@"customer"]) {
        WriteCustomerViewController *vc = [WriteCustomerViewController new];
        [vc setBlockSelectCustomer:^(DeviceUserInfoModel *model) {
            weakSelf.userType = @"1";
            weakSelf.userModel = model;
            weakSelf.userName = model.username;
            weakSelf.mobile = model.mobile;
            [weakSelf.tableView reloadData];
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - getter setter
- (NSMutableArray *)dataArray {
    return @[
             @[
                @{@"type":@"desc",@"title":@"设备编号:",@"content":self.deviceNo,},
                @{@"type":@"desc",@"title":@"设备名称:",@"content":self.deviceName,},
                @{@"type":@"desc",@"title":@"所在工区:",@"content":self.areaName,},
                @{@"type":@"list",@"data":self.deviceArray,},
                 ],
             @[
                @{@"type":@"desc",@"title":@"用户姓名:",@"content":self.userName,},
                @{@"type":@"desc",@"title":@"手机号码:",@"content":self.mobile,},
                @{@"type":@"list",@"data":self.userArray},
                @{@"type":@"button",@"title":@"保存",@"content":@"",},
                 ],

  ].mutableCopy;
}

- (NSArray *)deviceArray {
    return @[
             @{@"title":@"扫码获取",@"image":@"receive_scan_ic",@"sign":@"scandevice"},
             @{@"title":@"选择设备",@"image":@"receive_select_device_ic",@"sign":@"selectdevice"},
             ];
}

- (NSArray *)userArray {
    return @[
             @{@"title":@"扫码获取",@"image":@"receive_scan_ic",@"sign":@"scanuser"},
             @{@"title":@"选择用户",@"image":@"receive_select_user_ic",@"sign":@"selectuser"},
             @{@"title":@"访客填写",@"image":@"receive_visitor_write_ic",@"sign":@"customer"},
             ];
}

- (NSString *)userName {
    if (!_userName) {
        _userName = [GlobalManage sharedManage].userInfoModel.username?:@"";
    }
    return _userName;
}

- (NSString *)mobile {
    if (!_mobile) {
        _mobile = [GlobalManage sharedManage].userInfoModel.mobile?:@"";
    }
    return _mobile;
}

- (NSString *)deviceNo {
    if (!_deviceNo) {
        _deviceNo = @"";
    }
    return _deviceNo;
}

- (NSString *)deviceName {
    if (!_deviceName) {
        _deviceName = @"";
    }
    return _deviceName;
}

- (NSString *)areaName {
    if (!_areaName) {
        _areaName = @"";
    }
    return _areaName;
}

- (NSString *)userType {
    if (!_userType) {
        _userType = @"0";
    }
    return _userType;
}

- (void)setSelectDeviceModel:(DeviceInfoModel *)selectDeviceModel {
    _selectDeviceModel = selectDeviceModel;
    self.deviceNo = selectDeviceModel.deviceid;
    self.deviceName = selectDeviceModel.device_name;
    self.areaName = selectDeviceModel.area_name;
}

- (void)setModel:(DeviceStatisticModel *)model {
    _model = model;
//    self.deviceNo = model.deviceid?:@"";
//    self.deviceName = model.device_name?:@"";
//    self.areaName = model.area_name?:@"";
    DeviceInfoModel *device = [DeviceInfoModel new];
    device.device_name = model.device_name;
    device.deviceid = model.deviceid;
    device.area_name = model.area_name;
    device.device_name = model.device_name;
    device.typecode = model.typecode;
    self.selectDeviceModel = device;
    [self.tableView reloadData];
}
@end
